<template>
  <inline-Modal
    :visible="visible"
    title="本月重点工程进展"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="loading"
      @click="handelOk()"
      v-if="operateType == 2"
    >
      确定
    </a-button>
    <div class="currentMonth-page-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
        colon
      >
        <div class="sub-title">基本信息</div>
        <div class="base-container">
          <a-row :gutter="50">
            <a-col :span="8">
              <a-form-model-item label="例会月份">
                <a-month-picker
                  style="width:100%"
                  format="YYYY-MM"
                  valueFormat="YYYY-MM"
                  v-model="form.monthData"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="16">
              <a-form-model-item label="项目名称" prop="proCode">
                <a-select
                  placeholder="请选择"
                  v-model="form.proCode"
                  showSearch
                  :filter-option="filterOption"
                  @change="changeProject($event)"
                >
                  <a-select-option
                    :value="v.proCode"
                    v-for="v in projectSoucre"
                    :key="v.uuid"
                    :disabled="v.select"
                  >
                    {{ v.proName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="50">
            <a-col :span="8">
              <a-form-model-item label="所属区域">
                <a-select v-model="form.workArea" disabled>
                  <a-select-option
                    :value="v.dicItemCode"
                    v-for="v in regionSoucre"
                    :key="v.dicItemCode"
                  >
                    {{ v.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="16">
              <a-form-model-item label="项目单位" prop="projecUnit">
                <a-input
                  v-model="form.projecUnit"
                  placeholder="请输入"
                  :disabled="isDisabled"
                >
                </a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
        <a-divider />
        <div class="sub-title">本月重点工程进展</div>
        <div class="base-container">
          <a-form-model-item
            label="形象进度及完成情况"
            prop="progressAndCompletion"
          >
            <a-input
              placeholder="请输入"
              type="textarea"
              :rows="4"
              v-model="form.progressAndCompletion"
              :disabled="isDisabled"
            >
            </a-input>
          </a-form-model-item>
          <a-row :gutter="50">
            <a-col :span="8">
              <a-form-model-item label="本月产值" prop="outputValue">
                <a-input
                  v-model="form.outputValue"
                  placeholder="请输入"
                  :disabled="isDisabled"
                >
                </a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="年度累计投资">
                <a-input v-model="form.yearCompleteInvestment" disabled>
                </a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="年度计划投资">
                <a-input v-model="form.yearPlanInvestment" disabled> </a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="50">
            <a-col :span="12">
              <a-form-model-item label="项目累计产值">
                <a-input v-model="form.completedOutputValue" disabled>
                </a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="合同额">
                <a-input v-model="form.contractAmount" disabled> </a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item
            label="本月项目计划与实际完成对比"
            prop="planActualComparison"
          >
            <a-input
              placeholder="请输入"
              type="textarea"
              :rows="4"
              v-model="form.planActualComparison"
              :disabled="isDisabled"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="下月进度计划" prop="schedule">
            <a-input
              placeholder="请输入"
              type="textarea"
              :rows="4"
              v-model="form.schedule"
              :disabled="isDisabled"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="进度自评" prop="progressSelfAssessment">
            <a-input
              placeholder="请输入"
              type="textarea"
              :rows="4"
              v-model="form.progressSelfAssessment"
              :disabled="isDisabled"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="是否滞后" prop="laggingBehind">
            <a-radio-group v-model="form.laggingBehind" :disabled="isDisabled">
              <a-radio :value="1">
                是
              </a-radio>
              <a-radio :value="0">
                否
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            label="文件"
            prop="taskFiles"
            :rules="{
              required: true,
              message: '请选择文件',
            }"
          >
            <bjUploadFile
              :viewMode="isDisabled"
              type="file"
              :count="6"
              v-model="form.taskFiles"
              @download="downloadFile($event)"
              @change="upLoadFile($event, 'taskFiles')"
              @preview="viewFile($event)"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
        </div>
        <a-divider />
        <div class="sub-title">会议相关文件</div>
        <div class="base-container">
          <a-form-model-item
            label="会议材料"
            prop="conferenceMaterialsFiles"
            :rules="{
              required: true,
              message: '请选择会议材料',
            }"
          >
            <bjUploadFile
              :viewMode="isDisabled"
              type="file"
              :count="6"
              v-model="form.conferenceMaterialsFiles"
              @download="downloadFile($event)"
              @change="upLoadFile($event, 'conferenceMaterialsFiles')"
              @preview="viewFile($event)"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
          <a-form-model-item
            label="会议纪要"
            prop="meetingMinutesFiles"
            :rules="{
              required: true,
              message: '请选择会议纪要',
            }"
          >
            <bjUploadFile
              :viewMode="isDisabled"
              type="file"
              :count="6"
              v-model="form.meetingMinutesFiles"
              @download="downloadFile($event)"
              @change="upLoadFile($event, 'meetingMinutesFiles')"
              @preview="viewFile($event)"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
        </div>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </inline-Modal>
</template>

<script>
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/TopVUI";
import { downloadDfs } from "@/utils/TopVUI";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { getAllProListByQX, getDicItemByCode } from "@/api/common.js";
import { getTBRDetailByMonth, saveTBRData } from "@/api/safetyManage";
export default {
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      form: {
        uuid: "",
        //月份
        monthData: "",
        //项目
        proCode: undefined,
        //区域
        workArea: undefined,
        //项目单位
        projecUnit: "",
        //形象进度及完成情况
        progressAndCompletion: "",
        //本月产值
        outputValue: "",
        //年度累计投资
        yearCompleteInvestment: "",
        //年度计划投资
        yearPlanInvestment: "",
        //项目累计产值
        completedOutputValue: "",
        //合同额
        contractAmount: "",
        //本月项目计划与实际完成对比
        planActualComparison: "",
        //下月进度计划
        schedule: "",
        //进度自评
        progressSelfAssessment: "",
        //是否滞后
        laggingBehind: "",
        //文件
        taskFiles: [],
        //会议材料
        conferenceMaterialsFiles: [],
        //会议纪要
        meetingMinutesFiles: [],
      },
      rules: {
        proCode: [
          {
            required: true,
            message: "请选择项目",
          },
        ],
        projecUnit: [
          {
            required: true,
            message: "请输入项目单位",
          },
        ],
        progressAndCompletion: [
          {
            required: true,
            message: "请输入形象进度及完成情况",
          },
        ],
        outputValue: [
          {
            required: true,
            message: "请输入本月产值",
          },
        ],
        planActualComparison: [
          {
            required: true,
            message: "请输入本月项目计划与实际完成对比",
          },
        ],
        schedule: [
          {
            required: true,
            message: "请输入下月进度计划",
          },
        ],
        progressSelfAssessment: [
          {
            required: true,
            message: "请输入进度自评",
          },
        ],
        laggingBehind: [
          {
            required: true,
            message: "请选择是否滞后",
          },
        ],
      },
      //项目
      projectSoucre: [],
      //区域
      regionSoucre: [],
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    isDisabled() {
      if (this.operateType == 1) {
        return true;
      } else {
        return false;
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          let { monthData } = this.parameter;
          this.form.monthData = monthData;
          Promise.all([this.getProjectData(), this.getDicCodeData()]);
        }
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    //查询项目
    getProjectData() {
      return new Promise((resolve, reject) => {
        getAllProListByQX()
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询字典表
    getDicCodeData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "workArea" })
          .then((res) => {
            let { data } = res;
            this.regionSoucre = data;
            resolve();
          })
          .catch((_) => {
            this.regionSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    changeProject() {
      this.getDetail().finally((_) => {
        this.$refs.ruleForm.clearValidate();
      });
    },

    //详情
    getDetail() {
      let { monthData, proCode } = this.form;
      return new Promise((resolve, reject) => {
        getTBRDetailByMonth({ monthData, proCode })
          .then((res) => {
            let { data } = res;
            this.form.uuid = data?.uuid;
            //区域
            this.form.workArea = data?.workArea;
            //项目单位
            this.form.projecUnit = data?.projecUnit;
            //形象进度及完成情况
            this.form.progressAndCompletion = data?.progressAndCompletion;
            //本月产值
            this.form.outputValue = data?.outputValue;
            //年度累计投资
            this.form.yearCompleteInvestment = data?.yearCompleteInvestment;
            //年度计划投资
            this.form.yearPlanInvestment = data?.yearPlanInvestment;
            //项目累计产值
            this.form.completedOutputValue = data?.completedOutputValue;
            //合同额
            this.form.contractAmount = data?.contractAmount;
            //本月项目计划与实际完成对比
            this.form.planActualComparison = data?.planActualComparison;
            //下月进度计划
            this.form.schedule = data?.schedule;
            //进度自评
            this.form.progressSelfAssessment = data?.progressSelfAssessment;
            //是否滞后
            this.form.laggingBehind = data?.laggingBehind;
            //文件
            this.form.taskFiles = JSON.parse(data?.taskFiles ?? "[]");
            //会议材料
            this.form.conferenceMaterialsFiles = JSON.parse(
              data?.conferenceMaterialsFiles ?? "[]"
            );
            //会议纪要
            this.form.meetingMinutesFiles = JSON.parse(
              data?.meetingMinutesFiles ?? "[]"
            );
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            //月份
            monthData: form.monthData,
            //项目
            proCode: form.proCode,
            //区域
            workArea: form?.workArea ?? "",
            //项目单位
            projecUnit: form?.projecUnit ?? "",
            //形象进度及完成情况
            progressAndCompletion: form?.progressAndCompletion ?? "",
            //本月产值
            outputValue: form?.outputValue ?? "",
            //年度累计投资
            yearCompleteInvestment: form?.yearCompleteInvestment ?? "",
            //年度计划投资
            yearPlanInvestment: form?.yearPlanInvestment ?? "",
            //项目累计产值
            completedOutputValue: form?.completedOutputValue ?? "",
            //合同额
            contractAmount: form?.contractAmount ?? "",
            //本月项目计划与实际完成对比
            planActualComparison: form?.planActualComparison ?? "",
            //下月进度计划
            schedule: form?.schedule ?? "",
            //进度自评
            progressSelfAssessment: form?.progressSelfAssessment ?? "",
            //是否滞后
            laggingBehind: form?.laggingBehind ?? "",
            //文件
            taskFiles: JSON.stringify(form.taskFiles),
            //会议材料
            conferenceMaterialsFiles: JSON.stringify(
              form.conferenceMaterialsFiles
            ),
            //会议纪要
            meetingMinutesFiles: JSON.stringify(form.meetingMinutesFiles),
          };
          //编辑
          if (form.uuid) {
            this.$set(formJson, "uuid", form.uuid);
          }
          this.loading = true;
          saveTBRData(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.loading = false;
            });
        }
      });
    },
    handelCancel() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },
    //上传附件
    upLoadFile({ file, index }, attrName) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[attrName][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          const length = this.form[attrName].length - 1;
          this.$set(
            this.form[attrName][length],
            "dfsFileUuid",
            res.dfsFileUuid
          );
          this.$set(this.form[attrName][length], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form[attrName][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[attrName][index], "loading", false);
        });
    },
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.add-btn {
  position: absolute;
  top: 10px;
  right: 90px;
}
.currentMonth-page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
  padding: 10px 20px 20px 20px;
  box-sizing: border-box;
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 102px;
      white-space: pre-wrap;
      display: flex;
      justify-content: flex-end;
      line-height: 20px;
      margin-right: 2px;
      align-items: center;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
  .sub-title {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 16px;
    color: #111111;
    letter-spacing: 1px;
    margin-bottom: 10px;
  }
  .base-container {
    padding: 0 60px 0 0;
    .page-unit {
      position: absolute;
      right: -34px;
    }
    /deep/.bj-upload-file {
      .choosed-file-warp {
        width: 100%;
      }
    }
  }
  /deep/.ant-divider {
    margin: 10px 0;
  }
}
</style>
